package com.marketapp.dao;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;

import com.marketapp.domain.Equity;
import com.marketapp.domain.Sector;
import com.marketapp.helper.DaoException;
import com.marketapp.util.StringUtil;

public class EquityDaoImpl implements IEquityDao {

	@Autowired
	SessionFactory sessionFactory;

	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	@Override
	public List<Equity> getAllEquity() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<Equity> getAllEquityBySector(Sector equitySector) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void saveEquity(Equity equity) throws DaoException {

		Session session = sessionFactory.openSession();
		Transaction transaction = session.getTransaction();
		try {
			transaction.begin();
			session.save(equity);
			transaction.commit();
		} catch (Exception ex) {
			throw new DaoException("Error: Equity cannot be saved "
					+ equity.getEquityName(), ex.getCause());
		} finally {
			session.close();
		}
	}

	@Override
	public List<Equity> getAllEquityByName(String equityName)
			throws DaoException {
		List<Equity> equityListByName = new ArrayList<Equity>();
		Session session = sessionFactory.openSession();
		try {
			Query query = session.getNamedQuery("getAllEquityByName")
					.setString("equityName",
							StringUtil.getStringUpperCase(equityName) + "%");
			equityListByName = query.list();
		} catch (Exception e) {
			throw new DaoException("Error: Could not retrieve data",
					e.getCause());
		} finally {
			session.close();
		}
		return equityListByName;
	}

	@Override
	public List<Equity> checkIfEquityExists(String BSEID, String NSEID,
			String ISIN) throws DaoException {
		List<Equity> equityListByName = new ArrayList<Equity>();
		Session session = sessionFactory.openSession();
		try {
			Query query = session
					.getNamedQuery("getAllEquityByIdentifier")
					.setString("equityBSE",
							StringUtil.getStringUpperCase(BSEID))
					.setString("equityNSE",
							StringUtil.getStringUpperCase(NSEID))
					.setString("equityISIN",
							StringUtil.getStringUpperCase(ISIN));
			equityListByName = query.list();
		} catch (Exception e) {
			throw new DaoException("Error: Could not retrieve data",
					e.getCause());
		} finally {
			session.close();
		}
		return equityListByName;
	}

}
